package edu.utsa.cs.cs4953_2012.abacus;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * This enum encapsulates all the sound effects of a game, so as to separate the sound playing
 * codes from the game codes.
 * 1. Define all your sound effect names and the associated wave file.
 * 2. To play a specific sound, simply invoke SoundEffect.SOUND_NAME.play().
 * 3. You might optionally invoke the static method SoundEffect.init() to pre-load all the
 *    sound files, so that the play is not paused while loading the file for the first time.
 * 4. You can use the static variable SoundEffect.volume to mute the sound.
 */
public enum SoundEffect {
	CLICK("sound/click.wav");
	//BLIP("sound/blip.wav");//It's there if you find the click sound annoying...

	// Clip to manage the sound effect timeline
	private Clip clip;

	//Obviously sound control
	public static boolean soundOn = false;
	/**
	 * Constructor
	 * @param soundFileName A sound file. Use of the above constant is encouraged.
	 */
	SoundEffect(String soundFileName) {
		try {
			//Load sound file
			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFileName));
			// Get a clip resource.
			clip = AudioSystem.getClip();
			// Open audio clip and load samples from the audio input stream.
			clip.open(audioInputStream);
		} catch (UnsupportedAudioFileException e) {
			System.err.println(e.getMessage());
		} catch (IOException e) {
			System.err.println(e.getMessage());
		} catch (LineUnavailableException e) {
			System.err.println(e.getMessage());
		}
	}
	/**
	 * CALL CONSTRUCTOR FOR ALL THE ELEMENTS
	 */
	static void init() {
		values();
	}
	/**
	 * Plays the sound effect from beginning.
	 */
	public void play() {
		if (soundOn) {
			if (clip.isRunning())
				clip.stop();   // Stop the player if it is still running
			clip.setFramePosition(0); // rewind to the beginning
			clip.start();     // Start playing
		}
	}
}
